﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using SuporeSliplampApp.Models;
using SuporeSliplampApp.Util;
using SuporeSliplampApp.ViewModels;
using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using Emgu.CV.UI;
using Emgu.CV.Util;
using Color = System.Drawing.Color;
using Point = System.Drawing.Point;
using Rectangle = System.Drawing.Rectangle;
using Size = System.Drawing.Size;
using static SuporeSliplampApp.Util.util;
using System.Windows.Ink;
using System.Drawing;
using Brushes = System.Windows.Media.Brushes;
using Image = System.Windows.Controls.Image;
using System.Collections;
using ZedGraph;
using System.Windows.Media.Media3D;
using SuporeSliplampApp.Control;
using System.Windows.Forms;
using Org.BouncyCastle.Math.EC.Multiplier;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar;
using SuporeSliplampApp.Base;
using System.Threading;
using System.IO;

namespace SuporeSliplampApp.Views
{
    /// <summary>
    /// PicEditView.xaml 的交互逻辑
    /// </summary>
    public partial class PicEditView : Window
    {


        public string myPath;
        private DrawingAttributes drawingAttributes;
        Emgu.CV.Image<Bgr, byte> src;
        Mat img1, mask, final;
        double area = 0;
        int imgWid = 0, imgHid = 0;

        double originalImgHeight = 0;
        double originalImgWidth = 0;

        System.Windows.Media.Brush brush = (System.Windows.Media.Brush)new BrushConverter().ConvertFrom("#33FF3C");
        public ListControlModel picEditViewModel = new ListControlModel();
        public PicInputModel picInputModel { set; get; } = new PicInputModel();

        public static event EventHandler<ListControlModel> analyseDalegate;
        public static event EventHandler<ListControlModel> newDelegate;

        public event EventHandler timerStartEven;

        public static int SelectedImgIndex = 0;

        private Image imgShow1;
        private Image imgShow2;
        private Image imgShow3;
        private Image imgShow4;

        private double MinScale = 1.0;


        private bool isDeleteMode = false;

        private System.Windows.Point startPoint;
        private System.Windows.Shapes.Line currentLine;
        private System.Windows.Shapes.Line currentArrowLine;
        private System.Windows.Shapes.Ellipse currentEllipse;
        private System.Windows.Shapes.Rectangle currentRectangle;
        private List<System.Windows.Shapes.Line> drawnLines = new List<System.Windows.Shapes.Line>();
        private List<System.Windows.Shapes.Shape> drawnShapes = new List<System.Windows.Shapes.Shape>();
        private List<System.Windows.Controls.TextBlock> drawnLineLengths = new List<System.Windows.Controls.TextBlock>();
        private List<System.Windows.Controls.TextBlock> drawnShapeTexts = new List<System.Windows.Controls.TextBlock>();
        private List<System.Windows.Controls.TextBox> drawnTextBoxes = new List<System.Windows.Controls.TextBox>(); // 存储生成的文本框

        private System.Windows.Point firstLineStartPoint;
        private System.Windows.Point firstLineEndPoint;
        private System.Windows.Point secondLineEndPoint;
        private System.Windows.Shapes.Line firstLine;
        private System.Windows.Shapes.Line secondLine;
        private int clickCount = 0; // 用于追踪点击次数
        private System.Windows.Controls.TextBlock angleTextBlock;
        private List<System.Windows.Controls.TextBlock> drawnAngleTexts = new List<System.Windows.Controls.TextBlock>(); // 存储角度文本


        //分组管理
        public class DrawnObject
        {
            public List<UIElement> Elements { get; } = new List<UIElement>();
        }
        private List<DrawnObject> drawnObjects = new List<DrawnObject>();


        private SolidColorBrush selectedBrush = new SolidColorBrush(Colors.Green);
        private double currentThickness = 2;

        //画图倍率等
        private string selectedUnit = "pix";
        private double selectedMultiplier = 1.0;

        private double zoomindex = 1;

        public PicEditView(ListControlModel picModel)
        {
            InitializeComponent();

            OSDView.osodDelegate += OSDView_osodDelegate;

            this.picEditViewModel = picModel;
            this.DataContext = picEditViewModel;
            //Unloaded += EditPicControl_Unloaded;
            drawingAttributes = new DrawingAttributes();
            ImgShow.Source = new BitmapImage(new Uri(picEditViewModel.ImgPath));

            ticks.SelectedIndex = 0;
            //Multiplier.SelectedIndex = 0;

            imgWid = (int)this.ImgShow.Source.Width;
            imgHid = (int)this.ImgShow.Source.Height;
            this.Closed += PicEditView_Closed;
            this.Loaded += PicEditView_Loaded;
        }

        private void PicEditView_Loaded(object sender, RoutedEventArgs e)
        {
            double x = ImgShow.ActualHeight;
            double y = ImgShow.ActualWidth;

            imgShow1 = this.FindName("ImgShow") as Image;
            imgShow2 = this.FindName("ImgShow2") as Image;
            imgShow3 = this.FindName("ImgShow3") as Image;
            imgShow4 = this.FindName("ImgShow4") as Image;



        }

        private void PicEditView_Closed(object sender, EventArgs e)
        {
            //timerStartEven.Invoke(this, null);
            Common.isselectedindex = 0;
        }

        private void ConfirmBtn_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }



        private void CacelBtn_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
            CameraView.picEditView = null;
            util.ComboBox_SelectedIndex = 0;
            util.Image_SelectedIndex = 1;
        }



        private void AnylyBtn_Click(object sender, RoutedEventArgs e)
        {
            if (Common.isselectedindex == 0)
            {
                OSDView oSDView = new OSDView();
                oSDView.Owner = this;
                oSDView.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                oSDView.ShowDialog();
                return;
            }
            ImageAnalyse();
        }


        private void Ticks_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (ticks.SelectedItem is ComboBoxItem selectedItem)
            {
                selectedUnit = selectedItem.Content.ToString();
            }
        }

        //private void Multiplier_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        //{
        //    if (Multiplier.SelectedItem is ComboBoxItem selectedItem)
        //    {
        //        string multiplierText = selectedItem.Content.ToString().Replace("x", "");   
        //        if (double.TryParse(multiplierText, out double multiplier))
        //        {
        //            selectedMultiplier = multiplier;
        //        }
        //    }
        //}




        public void AddPic(ListControlModel model)
        {

        }
        private void ImageAnalyse()
        {
            src = new Image<Bgr, byte>(picEditViewModel.ImgPath);
            img1 = src.Clone().Mat;
            CvInvoke.Resize(img1, img1, new System.Drawing.Size(imgWid, imgHid));
            //CvInvoke.Imshow("img1", img1);
            var list = ink.Strokes;
            VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint();
            foreach (var item in list)
            {
                VectorOfPoint vectorOfPoint = new VectorOfPoint();
                foreach (var stylusPoint in item.StylusPoints)
                {
                    vectorOfPoint.Push(new System.Drawing.Point[] { new System.Drawing.Point((int)(stylusPoint.X), (int)(stylusPoint.Y)) });
                }
                if (vectorOfPoint.Size <= 0)
                    break;
                contours.Push(vectorOfPoint);
                final = Mat.Zeros(img1.Rows, img1.Cols, DepthType.Cv8U, 3);
                mask = Mat.Zeros(img1.Rows, img1.Cols, DepthType.Cv8U, 1);


                for (int i = 0; i < contours.Size; i++)
                {
                    CvInvoke.DrawContours(mask, contours, i, new MCvScalar(255, 255, 255), -1, Emgu.CV.CvEnum.LineType.AntiAlias);
                }

                CvInvoke.BitwiseAnd(img1, img1, final, mask);

                int b = bSums(mask);
                if (Common.languageCode == "zh-CN")
                {
                    Console.WriteLine("白色点数：b=" + b.ToString());
                }
                else
                {
                    Console.WriteLine("White Points：b=" + b.ToString());
                }
                //Console.WriteLine("白色点数：b=" + b.ToString());
                //CvInvoke.Imshow("final", final);

                Mat img_gray = new Mat();
                Mat result = new Mat();
                Mat clahe_result = new Mat();
                CvInvoke.CvtColor(final, img_gray, ColorConversion.Bgr2Gray);
                //CvInvoke.CvtColor(final, img_gray, ColorConversion.Rgb2Gray);
                //CvInvoke.Imshow("img_gray", img_gray);

                Mat clahe_result2 = new Mat();
                CvInvoke.CLAHE(img_gray, 10, new Size(8, 8), clahe_result2);


                Mat crs = clahe_result2.Clone();
                CvInvoke.CLAHE(clahe_result2, 8, new Size(40, 40), clahe_result2);


                Mat cr = clahe_result2.Clone();
                CvInvoke.Threshold(clahe_result2, clahe_result2, 60, 255, ThresholdType.Otsu);


                Mat se = CvInvoke.GetStructuringElement(0, new Size(3, 3), new Point(-1, -1));
                CvInvoke.Erode(clahe_result2, clahe_result2, se, new Point(-1, -1), 2, BorderType.Default, new MCvScalar());
                CvInvoke.Dilate(clahe_result2, clahe_result2, se, new Point(-1, -1), 3, BorderType.Default, new MCvScalar());



                Mat imBin = new Mat();
                CvInvoke.Threshold(clahe_result2, imBin, 20, 255, ThresholdType.Otsu);


                VectorOfVectorOfPoint contours2 = new VectorOfVectorOfPoint();
                CvInvoke.FindContours(imBin, contours2, null, RetrType.Ccomp, ChainApproxMethod.ChainApproxNone);
                CvInvoke.CvtColor(clahe_result2, clahe_result2, ColorConversion.Gray2Rgb);

                area = CvInvoke.ContourArea(contours2[0], true);

                Mat src1 = img1.Clone();
                CvInvoke.CvtColor(cr, cr, ColorConversion.Gray2Rgb);

                int a = bSums(clahe_result2);
                if (Common.languageCode == "zh-CN")
                {
                    Console.WriteLine("统计a=" + a.ToString());
                }
                else
                {
                    Console.WriteLine("Stats a=" + a.ToString());
                }
                //Console.WriteLine("统计a=" + a.ToString());
                if (b == 0)
                {
                    if (Common.languageCode == "zh-CN")
                    {
                        MessageView messageView = new MessageView("掩膜图像 mask 中无白色像素点！", 0);
                        messageView.Owner = System.Windows.Application.Current.Windows.OfType<Window>().FirstOrDefault(w => w.IsActive);
                        messageView.ShowDialog();
                    }
                    else
                    {
                        MessageView messageView = new MessageView("No white pixels!", 0);
                        messageView.Owner = System.Windows.Application.Current.Windows.OfType<Window>().FirstOrDefault(w => w.IsActive);
                        messageView.ShowDialog();
                    }
                    return;
                }

                int c = (b - a) * 100 / b;
                if (Common.languageCode == "zh-CN")
                {
                    Console.WriteLine("缺失率c=" + c.ToString());
                }
                else
                {
                    Console.WriteLine("Missing Rate c=" + c.ToString());
                }
                //Console.WriteLine("缺失率c=" + c.ToString());
                cr.CopyTo(src1);


                Mat mask2 = new Mat();
                CvInvoke.CvtColor(crs, mask2, ColorConversion.Gray2Rgb);
                mask2 = ColorTemprature(mask2, 100);
                CvInvoke.CvtColor(mask2, mask2, ColorConversion.Bgr2Bgra);
                mask2 = SetTransparnt(mask2);
                //CvInvoke.Imshow("mask2", mask2);
                CvInvoke.Imwrite("alpha.png", mask2);
                CvInvoke.DrawContours(mask2, contours2, -1, new MCvScalar(0, 255, 0));

                Mat srcImage1 = img1.Clone();
                CvInvoke.CvtColor(srcImage1, srcImage1, ColorConversion.Bgr2Bgra);
                Mat srcImage2 = mask2.Clone();
                CvInvoke.CvtColor(srcImage2, srcImage2, ColorConversion.Bgr2Bgra);
                Mat imageRoi = new Mat(srcImage1, new Rectangle(0, 0, mask2.Cols, mask2.Rows));
                Mat mask3 = mask2.Clone();

                srcImage2.CopyTo(imageRoi, mask3);
                //CvInvoke.PutText(imageRoi, "缺失率：" + c.ToString(), new System.Drawing.Point(30, 60), Emgu.CV.CvEnum.FontFace.HersheyPlain, 2.5,
                //new MCvScalar(255, 255, 255));

                string content;
                if (Common.languageCode == "zh-CN")
                {
                    content = "缺失率：";
                }
                else
                {
                    content = "Missing Rate :";
                }

                using (Graphics g = Graphics.FromImage(imageRoi.Bitmap))
                {
                    Font font = new Font("宋体", 50);
                    SolidBrush brush = new SolidBrush(Color.Red);
                    g.DrawString(content + c.ToString(), font, brush, new PointF(10, 30));
                }

                //CvInvoke.Imshow("imageRoi", imageRoi);
                //CvInvoke.Imshow("srcImage1", srcImage1);
                //CvInvoke.Imshow("srcImage2", srcImage2);
                string path = Common.comPath + @"\" + picEditViewModel.Name + "_1.jpg";
                imageRoi.Save(path);
                ListControlModel listControlModel = new ListControlModel();
                listControlModel.ImgPath = path;
                listControlModel.Name = picEditViewModel.Name + "_1";
                analyseDalegate.Invoke(this, listControlModel);
            }
        }

        private void AnaBtn_Click(object sender, RoutedEventArgs e)
        {
            setCavasEnable();
        }

        private void setCavasEnable()
        {
            if (!ink.IsEnabled)
            {
                ink.IsEnabled = true;
            }
            ink.DefaultDrawingAttributes.Color = Colors.GreenYellow;
            ink.EditingMode = InkCanvasEditingMode.Ink;
            ink.DefaultDrawingAttributes.Height = 2;
            ink.DefaultDrawingAttributes.Width = 2;

        }


        private string GetFormattedLength(double length)
        {
            switch (selectedUnit)
            {
                case "pix":
                    return $"{length:F2} px";
                case "mm":
                    double lengthInMm = ConvertPixelsToMm(length) / selectedMultiplier;
                    return $"{lengthInMm:F2} mm";
                case "N/A":
                    return string.Empty;
                default:
                    return string.Empty;
            }
        }

        private string GetFormattedRectangleText(double width, double height)
        {
            switch (selectedUnit)
            {
                case "pix":
                    double perimeter = 2 * (width + height);
                    double area = width * height;
                    return $"P: {perimeter:F2} px, A: {area:F2} px²";
                case "mm":
                    double widthInMm = ConvertPixelsToMm(width) / selectedMultiplier;
                    double heightInMm = ConvertPixelsToMm(height) / selectedMultiplier;
                    double perimeterInMm = 2 * (widthInMm + heightInMm);
                    double areaInMm2 = widthInMm * heightInMm;
                    return $"P: {perimeterInMm:F2} mm, A: {areaInMm2:F2} mm²";
                case "N/A":
                    return string.Empty;
                default:
                    return string.Empty;
            }
        }

        private string GetFormattedCircleText(double radius)
        {
            switch (selectedUnit)
            {
                case "pix":
                    double circumference = 2 * System.Math.PI * radius;
                    double area = System.Math.PI * radius * radius;
                    return $"C: {circumference:F2} px, A: {area:F2} px²";
                case "mm":
                    double radiusInMm = ConvertPixelsToMm(radius) / selectedMultiplier;
                    double circumferenceInMm = 2 * System.Math.PI * radiusInMm;
                    double areaInMm2 = System.Math.PI * radiusInMm * radiusInMm;
                    return $"C: {circumferenceInMm:F2} mm, A: {areaInMm2:F2} mm²";
                case "N/A":
                    return string.Empty;
                default:
                    return string.Empty;
            }
        }


        private double ConvertPixelsToMm(double pixels)
        {
            const double pixelToMmFactor = 25.4 / 96;
            return pixels * pixelToMmFactor;
        }



        private void ClearDrawingEvents()
        {
            isDeleteMode = false;

            //ink.MouseLeftButtonDown -= InkCanvas_MouseLeftButtonDown_Delete;
            ink.PreviewMouseLeftButtonDown -= InkCanvas_MouseLeftButtonDown_Delete;

            ink.MouseDown -= InkCanvas_MouseDown_Line;
            ink.MouseMove -= InkCanvas_MouseMove_Line;
            ink.MouseUp -= InkCanvas_MouseUp_Line;

            ink.MouseDown -= InkCanvas_MouseDown_Arrow;
            ink.MouseMove -= InkCanvas_MouseMove_Arrow;
            ink.MouseUp -= InkCanvas_MouseUp_Arrow;

            ink.MouseDown -= InkCanvas_MouseDown_Circle;
            ink.MouseMove -= InkCanvas_MouseMove_Circle;
            ink.MouseUp -= InkCanvas_MouseUp_Circle;

            ink.MouseDown -= InkCanvas_MouseDown_Rectangle;
            ink.MouseMove -= InkCanvas_MouseMove_Rectangle;
            ink.MouseUp -= InkCanvas_MouseUp_Rectangle;

            ink.MouseLeftButtonDown -= InkCanvas_MouseClick_Angle;
            ink.MouseMove -= InkCanvas_MouseMove_Angle;

            ink.MouseLeftButtonDown -= InkCanvas_MouseLeftButtonDown_AddTextBox;

            ink.EditingMode = InkCanvasEditingMode.None;

        }

        //绘制直线
        private void Line_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (Common.isselectedindex == 0)
            {
                OSDView oSDView = new OSDView();
                oSDView.Owner = this;
                oSDView.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                oSDView.ShowDialog();
            }
            else
            {
                ClearDrawingEvents();
                ink.MouseDown += InkCanvas_MouseDown_Line;
                ink.MouseMove += InkCanvas_MouseMove_Line;
                ink.MouseUp += InkCanvas_MouseUp_Line;
            }

        }

        private void InkCanvas_MouseDown_Line(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            startPoint = e.GetPosition(ink);
            currentLine = new System.Windows.Shapes.Line
            {
                Stroke = selectedBrush,
                StrokeThickness = currentThickness,
                X1 = startPoint.X,
                Y1 = startPoint.Y,
                X2 = startPoint.X,
                Y2 = startPoint.Y
            };
            ink.Children.Add(currentLine);
        }

        private void InkCanvas_MouseMove_Line(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (currentLine != null)
            {
                System.Windows.Point endPoint = e.GetPosition(ink);
                currentLine.X2 = endPoint.X;
                currentLine.Y2 = endPoint.Y;
            }
        }

        private void InkCanvas_MouseUp_Line(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (currentLine == null)
            {
                return;
            }

            var lineGroup = new DrawnObject();
            lineGroup.Elements.Add(currentLine);

            double length = System.Math.Sqrt(System.Math.Pow(currentLine.X2 - currentLine.X1, 2) + System.Math.Pow(currentLine.Y2 - currentLine.Y1, 2));
            string lengthTextContent = GetFormattedLength(length);

            if (!string.IsNullOrEmpty(lengthTextContent))
            {
                var lengthText = new System.Windows.Controls.TextBlock
                {
                    Text = lengthTextContent,
                    Foreground = selectedBrush,
                    FontSize = 14,
                };
                ink.Children.Add(lengthText);

                double midX = (currentLine.X1 + currentLine.X2) / 2;
                double midY = (currentLine.Y1 + currentLine.Y2) / 2;

                System.Windows.Media.TranslateTransform translateTransform = new System.Windows.Media.TranslateTransform(midX + 5, midY + 5);
                lengthText.RenderTransform = translateTransform;

                ////ink.Children.Add(lengthText);
                //drawnLineLengths.Add(lengthText);
                lineGroup.Elements.Add(lengthText);  //test
            }

            drawnObjects.Add(lineGroup);  //test
            //drawnLines.Add(currentLine);
            currentLine = null;

        }

        //绘制箭头
        private void Arrow_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (Common.isselectedindex == 0)
            {
                OSDView oSDView = new OSDView();
                oSDView.Owner = this;
                oSDView.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                oSDView.ShowDialog();
                return;
            }
            ClearDrawingEvents();
            ink.MouseDown += InkCanvas_MouseDown_Arrow;
            ink.MouseMove += InkCanvas_MouseMove_Arrow;
            ink.MouseUp += InkCanvas_MouseUp_Arrow;
        }

        private void InkCanvas_MouseDown_Arrow(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            startPoint = e.GetPosition(ink);
            currentArrowLine = new System.Windows.Shapes.Line
            {
                Stroke = selectedBrush,
                StrokeThickness = currentThickness,
                X1 = startPoint.X,
                Y1 = startPoint.Y,
                X2 = startPoint.X,
                Y2 = startPoint.Y
            };
            ink.Children.Add(currentArrowLine);
        }

        private void InkCanvas_MouseMove_Arrow(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (currentArrowLine != null)
            {
                System.Windows.Point endPoint = e.GetPosition(ink);
                currentArrowLine.X2 = endPoint.X;
                currentArrowLine.Y2 = endPoint.Y;
            }
        }

        private void InkCanvas_MouseUp_Arrow(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (currentArrowLine == null)
            {
                return;
            }

            var arrowGroup = new DrawnObject();

            double deltaX = currentArrowLine.X2 - currentArrowLine.X1;
            double deltaY = currentArrowLine.Y2 - currentArrowLine.Y1;
            double angle = Math.Atan2(deltaY, deltaX);

            double arrowLength = Math.Max(currentThickness * 5, 10);
            double arrowWidth = currentThickness * 2;

            // 计算箭头的左右两边线的终点
            System.Windows.Point arrowLeft = new System.Windows.Point(
                currentArrowLine.X2 - arrowLength * Math.Cos(angle - Math.PI / 6),
                currentArrowLine.Y2 - arrowLength * Math.Sin(angle - Math.PI / 6)
            );

            System.Windows.Point arrowRight = new System.Windows.Point(
                currentArrowLine.X2 - arrowLength * Math.Cos(angle + Math.PI / 6),
                currentArrowLine.Y2 - arrowLength * Math.Sin(angle + Math.PI / 6)
            );

            System.Windows.Shapes.Line leftArrowLine = new System.Windows.Shapes.Line
            {
                Stroke = selectedBrush,
                StrokeThickness = currentThickness,
                X1 = currentArrowLine.X2,
                Y1 = currentArrowLine.Y2,
                X2 = arrowLeft.X,
                Y2 = arrowLeft.Y
            };
            ink.Children.Add(leftArrowLine);

            System.Windows.Shapes.Line rightArrowLine = new System.Windows.Shapes.Line
            {
                Stroke = selectedBrush,
                StrokeThickness = currentThickness,
                X1 = currentArrowLine.X2,
                Y1 = currentArrowLine.Y2,
                X2 = arrowRight.X,
                Y2 = arrowRight.Y
            };
            ink.Children.Add(rightArrowLine);

            //drawnLines.Add(currentArrowLine);
            //drawnLines.Add(leftArrowLine);
            //drawnLines.Add(rightArrowLine);

            arrowGroup.Elements.Add(currentArrowLine);
            arrowGroup.Elements.Add(leftArrowLine);
            arrowGroup.Elements.Add(rightArrowLine);
            drawnObjects.Add(arrowGroup);         //lhz

            currentArrowLine = null;
        }



        //绘制圆
        private void Circle_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (Common.isselectedindex == 0)
            {
                OSDView oSDView = new OSDView();
                oSDView.Owner = this;
                oSDView.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                oSDView.ShowDialog();
                return;
            }
            ClearDrawingEvents();
            ink.MouseDown += InkCanvas_MouseDown_Circle;
            ink.MouseMove += InkCanvas_MouseMove_Circle;
            ink.MouseUp += InkCanvas_MouseUp_Circle;
        }

        private void InkCanvas_MouseDown_Circle(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            startPoint = e.GetPosition(ink);
            currentEllipse = new System.Windows.Shapes.Ellipse
            {
                Stroke = selectedBrush,
                StrokeThickness = currentThickness,
            };

            currentEllipse.Width = 0;
            currentEllipse.Height = 0;

            var transform = new TranslateTransform(startPoint.X, startPoint.Y);
            currentEllipse.RenderTransform = transform;

            ink.Children.Add(currentEllipse);
        }

        private void InkCanvas_MouseMove_Circle(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (currentEllipse != null)
            {
                System.Windows.Point currentPosition = e.GetPosition(ink);

                double radius = System.Math.Max(System.Math.Abs(currentPosition.X - startPoint.X), System.Math.Abs(currentPosition.Y - startPoint.Y));

                currentEllipse.Width = 2 * radius;
                currentEllipse.Height = 2 * radius;

                var transform = new TranslateTransform(startPoint.X - radius, startPoint.Y - radius);
                currentEllipse.RenderTransform = transform;
            }
        }



        private void InkCanvas_MouseUp_Circle(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (currentEllipse == null)
            {
                return;
            }

            var circleGroup = new DrawnObject();
            circleGroup.Elements.Add(currentEllipse);

            double radius = currentEllipse.Width / 2;
            //double circumference = 2 * System.Math.PI * radius;
            //double area = System.Math.PI * radius * radius;

            string textContent = GetFormattedCircleText(radius);

            if (!string.IsNullOrEmpty(textContent))
            {
                var textBlock = new System.Windows.Controls.TextBlock
                {
                    Text = textContent,
                    Foreground = selectedBrush,
                    FontSize = 14
                };

                double centerX = startPoint.X;
                double centerY = startPoint.Y;

                var transform = new System.Windows.Media.TranslateTransform(centerX - textBlock.ActualWidth / 2, centerY - textBlock.ActualHeight / 2);
                textBlock.RenderTransform = transform;

                //ink.Children.Add(textBlock);
                //drawnShapeTexts.Add(textBlock);
                circleGroup.Elements.Add(textBlock);
                ink.Children.Add(textBlock);  //lhz
            }

            //drawnShapes.Add(currentEllipse);

            drawnObjects.Add(circleGroup);
            currentEllipse = null;

        }



        //绘制方形
        private void Rectangle_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (Common.isselectedindex == 0)
            {
                OSDView oSDView = new OSDView();
                oSDView.Owner = this;
                oSDView.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                oSDView.ShowDialog();
                return;
            }
            ClearDrawingEvents();
            ink.MouseDown += InkCanvas_MouseDown_Rectangle;
            ink.MouseMove += InkCanvas_MouseMove_Rectangle;
            ink.MouseUp += InkCanvas_MouseUp_Rectangle;
        }

        private void InkCanvas_MouseDown_Rectangle(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            startPoint = e.GetPosition(ink);
            currentRectangle = new System.Windows.Shapes.Rectangle
            {
                Stroke = selectedBrush,
                StrokeThickness = currentThickness,
            };

            currentRectangle.Width = 0;
            currentRectangle.Height = 0;

            var transform = new TranslateTransform(startPoint.X, startPoint.Y);
            currentRectangle.RenderTransform = transform;

            ink.Children.Add(currentRectangle);
        }

        private void InkCanvas_MouseMove_Rectangle(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (currentRectangle != null)
            {
                System.Windows.Point currentPosition = e.GetPosition(ink);

                //double sideLength = System.Math.Max(System.Math.Abs(currentPosition.X - startPoint.X), System.Math.Abs(currentPosition.Y - startPoint.Y));
                double width = System.Math.Abs(currentPosition.X - startPoint.X);
                double height = System.Math.Abs(currentPosition.Y - startPoint.Y);

                currentRectangle.Width = width;
                currentRectangle.Height = height;

                var transform = new TranslateTransform(Math.Min(startPoint.X, currentPosition.X), Math.Min(startPoint.Y, currentPosition.Y));
                currentRectangle.RenderTransform = transform;
            }
        }


        private void InkCanvas_MouseUp_Rectangle(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (currentRectangle == null)
            {
                return;
            }

            var rectGroup = new DrawnObject();
            rectGroup.Elements.Add(currentRectangle);

            double width = currentRectangle.Width;
            double height = currentRectangle.Height;
            //double perimeter = 2 * (width + height);
            //double area = width * height;

            string textContent = GetFormattedRectangleText(width, height);

            if (!string.IsNullOrEmpty(textContent))
            {
                var textBlock = new System.Windows.Controls.TextBlock
                {
                    Text = textContent,
                    Foreground = selectedBrush,
                    FontSize = 14
                };

                double centerX = startPoint.X;
                double centerY = startPoint.Y;

                var transform = new System.Windows.Media.TranslateTransform(centerX - textBlock.ActualWidth / 2, centerY - textBlock.ActualHeight / 2);
                textBlock.RenderTransform = transform;

                rectGroup.Elements.Add(textBlock);
                ink.Children.Add(textBlock);
                //drawnShapeTexts.Add(textBlock);
            }

            //drawnShapes.Add(currentRectangle);
            drawnObjects.Add(rectGroup);
            currentRectangle = null;

        }



        private void Angle_Click(object sender, RoutedEventArgs e)
        {
            if (Common.isselectedindex == 0)
            {
                OSDView oSDView = new OSDView();
                oSDView.Owner = this;
                oSDView.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                oSDView.ShowDialog();
                return;
            }
            ClearDrawingEvents();
            ink.MouseLeftButtonDown += InkCanvas_MouseClick_Angle;
            ink.MouseMove += InkCanvas_MouseMove_Angle;
        }

        private DrawnObject currentAngleGroup;
        private void InkCanvas_MouseClick_Angle(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            System.Windows.Point currentPosition = e.GetPosition(ink);
            clickCount++;

            if (clickCount == 1)
            {
                currentAngleGroup = new DrawnObject();

                firstLineStartPoint = currentPosition;
                firstLine = new System.Windows.Shapes.Line
                {
                    Stroke = selectedBrush,
                    StrokeThickness = currentThickness,
                    X1 = firstLineStartPoint.X,
                    Y1 = firstLineStartPoint.Y,
                    X2 = firstLineStartPoint.X,
                    Y2 = firstLineStartPoint.Y
                };
                ink.Children.Add(firstLine);
            }
            else if (clickCount == 2)
            {
                firstLineEndPoint = currentPosition;
                firstLine.X2 = currentPosition.X;
                firstLine.Y2 = currentPosition.Y;

                //drawnLines.Add(firstLine);
                currentAngleGroup.Elements.Add(firstLine);  //lhz

                secondLine = new System.Windows.Shapes.Line
                {
                    Stroke = selectedBrush,
                    StrokeThickness = currentThickness,
                    X1 = firstLineEndPoint.X,
                    Y1 = firstLineEndPoint.Y,
                    X2 = firstLineEndPoint.X,
                    Y2 = firstLineEndPoint.Y
                };
                ink.Children.Add(secondLine);
            }
            else if (clickCount == 3)
            {
                secondLineEndPoint = currentPosition;
                secondLine.X2 = secondLineEndPoint.X;
                secondLine.Y2 = secondLineEndPoint.Y;

                currentAngleGroup.Elements.Add(secondLine);
                //drawnLines.Add(secondLine);

                DisplayAngle(firstLineStartPoint, firstLineEndPoint, secondLineEndPoint);

                drawnObjects.Add(currentAngleGroup);
                currentAngleGroup = null;

                clickCount = 0;
            }
        }

        private void InkCanvas_MouseMove_Angle(object sender, System.Windows.Input.MouseEventArgs e)
        {
            System.Windows.Point currentPosition = e.GetPosition(ink);

            if (clickCount == 1 && firstLine != null)
            {
                firstLine.X2 = currentPosition.X;
                firstLine.Y2 = currentPosition.Y;
            }
            else if (clickCount == 2 && secondLine != null)
            {
                secondLine.X2 = currentPosition.X;
                secondLine.Y2 = currentPosition.Y;
            }
        }

        private void DisplayAngle(System.Windows.Point firstLineStartPoint, System.Windows.Point vertexPoint, System.Windows.Point secondLineEndPoint)
        {
            if (selectedUnit == "N/A")
            {
                return;
            }

            double angle = CalculateAngle(firstLineStartPoint, vertexPoint, secondLineEndPoint);

            angleTextBlock = new System.Windows.Controls.TextBlock
            {
                Text = $"{angle:F2}°",
                Foreground = selectedBrush,
                FontSize = 14
            };
            ink.Children.Add(angleTextBlock);

            var transform = new System.Windows.Media.TranslateTransform(vertexPoint.X + 5, vertexPoint.Y + 5);
            angleTextBlock.RenderTransform = transform;

            //drawnAngleTexts.Add(angleTextBlock);
            currentAngleGroup.Elements.Add(angleTextBlock);
        }

        private double CalculateAngle(System.Windows.Point firstLineStartPoint, System.Windows.Point vertexPoint, System.Windows.Point secondLineEndPoint)
        {
            double v1X = firstLineStartPoint.X - vertexPoint.X;
            double v1Y = firstLineStartPoint.Y - vertexPoint.Y;
            double v2X = secondLineEndPoint.X - vertexPoint.X;
            double v2Y = secondLineEndPoint.Y - vertexPoint.Y;

            double dotProduct = v1X * v2X + v1Y * v2Y;
            double magnitudeV1 = Math.Sqrt(v1X * v1X + v1Y * v1Y);
            double magnitudeV2 = Math.Sqrt(v2X * v2X + v2Y * v2Y);

            double angleInRadians = Math.Acos(dotProduct / (magnitudeV1 * magnitudeV2));
            double angleInDegrees = angleInRadians * (180.0 / Math.PI);

            return angleInDegrees;
        }

        private void Mouse_Click(object sender, System.Windows.RoutedEventArgs e) { ClearDrawingEvents(); }




        private void Text_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (Common.isselectedindex == 0)
            {
                OSDView oSDView = new OSDView();
                oSDView.Owner = this;
                oSDView.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                oSDView.ShowDialog();
                return;
            }
            ClearDrawingEvents();
            ink.MouseLeftButtonDown += InkCanvas_MouseLeftButtonDown_AddTextBox;
        }

        private void InkCanvas_MouseLeftButtonDown_AddTextBox(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            // 获取点击的位置
            System.Windows.Point clickPosition = e.GetPosition(ink);

            var textGroup = new DrawnObject();

            // 创建新的TextBox
            var textBox = new System.Windows.Controls.TextBox
            {
                Width = 100, // 设置默认宽度
                FontSize = 14, // 设置字体大小
                Background = System.Windows.Media.Brushes.Transparent,
                BorderBrush = System.Windows.Media.Brushes.Green,
                BorderThickness = new System.Windows.Thickness(1),
                Margin = new Thickness(clickPosition.X, clickPosition.Y, 0, 0),
                Foreground = selectedBrush
            };
            
            textGroup.Elements.Add(textBox);
            
            ink.Children.Add(textBox);
            //drawnTextBoxes.Add(textBox); // 将TextBox添加到列表中
            drawnObjects.Add(textGroup);

            textBox.LostFocus += (s, args) =>
            {
                ConfirmTextBox(textBox);
            };
            textBox.Focus();

            textBox.LostFocus += (s, args) => ConfirmTextBox(textBox);
        }


        private void ConfirmTextBox(System.Windows.Controls.TextBox textBox)
        {
            textBox.IsReadOnly = true; // 设置为只读
            textBox.Background = System.Windows.Media.Brushes.Transparent; // 背景保持透明
            textBox.BorderBrush = System.Windows.Media.Brushes.Transparent; // 隐藏边框
            textBox.LostFocus -= (s, args) => ConfirmTextBox(textBox); // 移除失去焦点事件
        }



        private void Rub_Click(object sender, RoutedEventArgs e)
        {
            ClearDrawingEvents();
            isDeleteMode = true;
            ink.PreviewMouseLeftButtonDown += InkCanvas_MouseLeftButtonDown_Delete;
        }



        //private void InkCanvas_MouseLeftButtonDown_Delete(object sender, System.Windows.Input.MouseButtonEventArgs e)
        //{
        //    if (isDeleteMode)
        //    {
        //        System.Windows.Point clickPosition = e.GetPosition(ink);

        //        for (int i = drawnLines.Count - 1; i >= 0; i--)
        //        {
        //            var line = drawnLines[i];
        //            if (IsPointOnLine(clickPosition, line))
        //            {
        //                ink.Children.Remove(line);
        //                drawnLines.RemoveAt(i);

        //                if (i < drawnAngleTexts.Count)
        //                {
        //                    ink.Children.Remove(drawnAngleTexts[i]);
        //                    drawnAngleTexts.RemoveAt(i);
        //                }

        //                if (i < drawnLineLengths.Count)
        //                {
        //                    ink.Children.Remove(drawnLineLengths[i]);
        //                    drawnLineLengths.RemoveAt(i);
        //                }
        //            }
        //        }

        //        for (int i = drawnShapes.Count - 1; i >= 0; i--)
        //        {
        //            var shape = drawnShapes[i];
        //            if (IsPointInsideShape(clickPosition, shape))
        //            {
        //                ink.Children.Remove(shape);
        //                drawnShapes.RemoveAt(i);

        //                if (i < drawnShapeTexts.Count)
        //                {
        //                    ink.Children.Remove(drawnShapeTexts[i]);
        //                    drawnShapeTexts.RemoveAt(i);
        //                }
        //            }
        //        }

        //        for (int i = drawnTextBoxes.Count - 1; i >= 0; i--)
        //        {
        //            var textBox = drawnTextBoxes[i];
        //            if (IsPointNearTextBox(clickPosition, textBox))
        //            {
        //                ink.Children.Remove(textBox);
        //                drawnTextBoxes.RemoveAt(i);
        //            }
        //        }

        //    }
        //}


        private void InkCanvas_MouseLeftButtonDown_Delete(object sender, MouseButtonEventArgs e)
        {
            if (!isDeleteMode) return;

            var point = e.GetPosition(ink);
            UIElement hitElement = ink.InputHitTest(point) as UIElement;
            if (hitElement == null) return;

            var target = drawnObjects.FirstOrDefault(group => group.Elements.Contains(hitElement));
            if (target != null)
            {
                foreach (var element in target.Elements)
                {
                    ink.Children.Remove(element);
                }
                drawnObjects.Remove(target);
            }
        }

        //private bool IsElementHit(UIElement element, Point clickPos)
        //{
        //    const double hitTolerance = 15.0;

        //    if (element is Shape shape)
        //    {
        //        switch (shape)
        //        {
        //            case System.Windows.Shapes.Line line:
        //                return IsPointNearLine(clickPos, line, hitTolerance);

        //            case System.Windows.Shapes.  ellipse:
        //                return IsPointInEllipse(clickPos, ellipse);

        //            case Rectangle rect:
        //                return IsPointInRectangle(clickPos, rect);

        //            // 其他Shape类型（如有需要可扩展）
        //            default:
        //                return false;
        //        }
        //    }
        //    // 处理文本元素
        //    else if (element is TextBlock textBlock)
        //    {
        //        var transform = textBlock.RenderTransform as TranslateTransform;
        //        if (transform == null) return false;
        //        return new Rect(
        //            transform.X,
        //            transform.Y,
        //            textBlock.ActualWidth,
        //            textBlock.ActualHeight
        //        ).Contains(clickPos);
        //    }
        //    else if (element is TextBox textBox)
        //    {
        //        return new Rect(
        //            textBox.Margin.Left,
        //            textBox.Margin.Top,
        //            textBox.ActualWidth,
        //            textBox.ActualHeight
        //        ).Contains(clickPos);
        //    }

        //    return false;
        //}


        private bool IsPointOnLine(System.Windows.Point point, System.Windows.Shapes.Line line)
        {
            double distance = Math.Abs((line.Y2 - line.Y1) * point.X - (line.X2 - line.X1) * point.Y + line.X2 * line.Y1 - line.Y2 * line.X1) /
                              Math.Sqrt(Math.Pow(line.Y2 - line.Y1, 2) + Math.Pow(line.X2 - line.X1, 2));

            return distance < 15.0;
        }


        private bool IsPointInsideShape(System.Windows.Point point, System.Windows.Shapes.Shape shape)
        {
            if (shape is System.Windows.Shapes.Ellipse ellipse)
            {
                var transform = (TranslateTransform)ellipse.RenderTransform;
                double centerX = transform.X + ellipse.Width / 2;
                double centerY = transform.Y + ellipse.Height / 2;
                double radius = ellipse.Width / 2;

                double distance = Math.Sqrt(Math.Pow(point.X - centerX, 2) + Math.Pow(point.Y - centerY, 2));
                return distance <= radius + 5 && distance >= radius - 5;
            }
            else if (shape is System.Windows.Shapes.Rectangle rectangle)
            {
                var transform = (TranslateTransform)rectangle.RenderTransform;
                double left = transform.X;
                double top = transform.Y;
                double right = left + rectangle.Width;
                double bottom = top + rectangle.Height;

                bool nearLeftOrRight = (point.X >= left - 15 && point.X <= left + 15) ||
                                               (point.X >= right - 15 && point.X <= right + 15);
                bool nearTopOrBottom = (point.Y >= top - 15 && point.Y <= top + 15) ||
                                       (point.Y >= bottom - 15 && point.Y <= bottom + 15);

                return (nearLeftOrRight && point.Y >= top && point.Y <= bottom) ||
                       (nearTopOrBottom && point.X >= left && point.X <= right);
            }
            return false;
        }


        private bool IsPointNearTextBox(System.Windows.Point clickPosition, System.Windows.Controls.TextBox textBox)
        {
            double left = textBox.Margin.Left;
            double top = textBox.Margin.Top;
            double right = left + textBox.ActualWidth;
            double bottom = top + textBox.ActualHeight;

            double tolerance = 100.0;

            return (clickPosition.X >= left - tolerance && clickPosition.X <= right + tolerance) &&
                   (clickPosition.Y >= top - tolerance && clickPosition.Y <= bottom + tolerance);
        }



        private void Clear_Click(object sender, RoutedEventArgs e)
        {
            for (int i = ink.Children.Count - 1; i >= 0; i--)
            {
                var child = ink.Children[i];

                if (child is System.Windows.Shapes.Line ||
                    child is System.Windows.Shapes.Rectangle ||
                    child is System.Windows.Shapes.Ellipse ||
                    child is System.Windows.Controls.TextBox ||
                    child is System.Windows.Controls.TextBlock)
                {
                    ink.Children.RemoveAt(i);
                }
            }

            drawnTextBoxes.Clear();
            drawnLines.Clear();
            drawnShapes.Clear();
            drawnLineLengths.Clear();
            drawnShapeTexts.Clear();
            drawnAngleTexts.Clear();
        }



        private void Colour_Click(object sender, RoutedEventArgs e)
        {
            using (var colorDialog = new ColorDialog())
            {
                if (colorDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    var selectedColor = colorDialog.Color;
                    var mediaColor = System.Windows.Media.Color.FromArgb(selectedColor.A, selectedColor.R, selectedColor.G, selectedColor.B);

                    selectedBrush = new SolidColorBrush(mediaColor);
                }
            }
        }

        private void ThicknessButton_Click(object sender, RoutedEventArgs e)
        {
            // 显示或隐藏 Popup
            if (ThicknessPopup.IsOpen)
            {
                ThicknessPopup.IsOpen = false;
            }
            else
            {
                ThicknessPopup.IsOpen = true;
            }
        }

        private void ThicknessSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {

            ThicknessValueTextBlock.Text = $"{ThicknessSlider.Value:F1}";
            currentThickness = ThicknessSlider.Value + 2;

        }


        //private void ApplyZoomToImages(double zoom, System.Windows.Point mousePosition)
        //{
        //    ApplyZoomToImage(imgShow1, zoom, mousePosition);
        //    ApplyZoomToImage(imgShow2, zoom, mousePosition);
        //    ApplyZoomToImage(imgShow3, zoom, mousePosition);
        //    ApplyZoomToImage(imgShow4, zoom, mousePosition);
        //}


        //private void ApplyZoomToImage(Image image, double zoom, System.Windows.Point mousePosition)
        //{
        //    double MinScale = 0.5;
        //    ScaleTransform transform = image.LayoutTransform as ScaleTransform ?? new ScaleTransform(1, 1);
        //    double newScaleX = transform.ScaleX * zoom;
        //    double newScaleY = transform.ScaleY * zoom;


        //    if (newScaleX < MinScale) newScaleX = MinScale;
        //    if (newScaleY < MinScale) newScaleY = MinScale;

        //    System.Windows.Point relativePosition = mousePosition;

        //    //MessageBox.Show($"Mouse Position: {mousePosition}, Relative Position: {relativePosition}");

        //    transform.CenterX = relativePosition.X;
        //    transform.CenterY = relativePosition.Y;
        //    transform.ScaleX = newScaleX;
        //    transform.ScaleY = newScaleY;
        //    image.LayoutTransform = transform;

        //}



        //private void ink_MouseWheel(object sender, MouseWheelEventArgs e)
        //{
        //    InkCanvas inkCanvas = sender as InkCanvas;
        //    double zoom = e.Delta > 0 ? 1.1 : 0.9;
        //    var mouseOverElement = Mouse.DirectlyOver;

        //    if (mouseOverElement is Image image)
        //    {
        //        System.Windows.Point mousePosition = e.GetPosition(image);

        //        if (Allzoom.IsChecked is true) { ApplyZoomToImages(zoom, mousePosition); }
        //        else { ApplyZoomToImage((Image)image, zoom, mousePosition); }
        //    }

        //}


        private void ApplyZoomToImages(double zoom, System.Windows.Point mousePosition)
        {
            ApplyZoomToImage(ImgShow, zoom, mousePosition, border1);
            ApplyZoomToImage(ImgShow2, zoom, mousePosition, border2);
            ApplyZoomToImage(ImgShow3, zoom, mousePosition, border3);
            ApplyZoomToImage(ImgShow4, zoom, mousePosition, border4);
        }

        private void ApplyZoomToImage(Image image, double zoom, System.Windows.Point mousePosition, System.Windows.Controls.Border border)
        {
            double MinScale = 0.5;

            ScaleTransform transform = image.RenderTransform as ScaleTransform ?? new ScaleTransform(1, 1);
            double newScaleX = transform.ScaleX * zoom;
            double newScaleY = transform.ScaleY * zoom;

            if (newScaleX < MinScale) newScaleX = MinScale;
            if (newScaleY < MinScale) newScaleY = MinScale;

            // 获取图片相对于容器的位置
            var container = (FrameworkElement)image.Parent;
            var relativePosition = mousePosition;

            // 计算新的图片位置以保持图片在Border中心
            double offsetX = (border.ActualWidth / 2 - relativePosition.X) * (newScaleX - transform.ScaleX);
            double offsetY = (border.ActualHeight / 2 - relativePosition.Y) * (newScaleY - transform.ScaleY);

            // 更新 RenderTransform
            transform.CenterX = relativePosition.X;
            transform.CenterY = relativePosition.Y;
            transform.ScaleX = newScaleX;
            transform.ScaleY = newScaleY;
            image.RenderTransform = transform;

            // 更新 Image 的位置
            Canvas.SetLeft(image, Canvas.GetLeft(image) - offsetX);
            Canvas.SetTop(image, Canvas.GetTop(image) - offsetY);

            // 更新 Border 的 Clip 属性以限制图片在边界内显示
            var clipRect = new RectangleGeometry(new Rect(0, 0, border.ActualWidth, border.ActualHeight));
            border.Clip = clipRect;

            Thread.Sleep(50);
        }

        private void ink_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            InkCanvas inkCanvas = sender as InkCanvas;
            double zoom = e.Delta > 0 ? 1.1 : 0.909090909090909;
            var mouseOverElement = Mouse.DirectlyOver;

            if (mouseOverElement is Image image)
            {
                System.Windows.Point mousePosition = e.GetPosition(image);

                if (Allzoom.IsChecked == true) { ApplyZoomToImages(zoom, mousePosition); }
                else
                {
                    System.Windows.Controls.Border parentBorder = image.Parent as System.Windows.Controls.Border;

                    ApplyZoomToImage(image, zoom, mousePosition, parentBorder);
                    zoomindex = zoom * zoomindex;
                }
            }
            e.Handled = true;
        }




        private void Allzoom_Checked(object sender, RoutedEventArgs e) { }

        private void Allzoom_Unchecked(object sender, RoutedEventArgs e) { }



        private void ImgShow_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            //Image targetImage = sender as Image;
            //double zoom = e.Delta > 0 ? 1.1 : 0.9;

            //if (targetImage != null)
            //{
            //    // 针对特定图片进行缩放
            //    ApplyZoomToImage(targetImage, zoom);
            //}
            //else
            //{
            //    // 同步缩放所有图片
            //    ApplyZoomToImages(ink, zoom);
            //}
        }



        private void ImgShow_MouseWheel2(object sender, MouseWheelEventArgs e)
        {
            //Image image = sender as Image;
            //if (image == null) return;

            //System.Windows.Point position = e.GetPosition(image);
            //ScaleTransform transform = image.LayoutTransform as ScaleTransform;
            //if (transform == null)
            //{
            //    transform = new ScaleTransform();
            //    image.LayoutTransform = transform;
            //}
            //double zoom = e.Delta > 0 ? 1.1 : 0.9;
            //ApplyZoomToImage(image, zoom);

            //transform.CenterX = position.X;
            //transform.CenterY = position.Y;
            //transform.ScaleX *= zoom;
            //transform.ScaleY *= zoom;
        }

        private void ImgShow_MouseWheel3(object sender, MouseWheelEventArgs e)
        {
            //Image image = sender as Image;
            //System.Windows.Point position = e.GetPosition(image);
            //ScaleTransform transform = image.LayoutTransform as ScaleTransform;

            //double zoom = e.Delta > 0 ? 1.1 : 0.9;

            //transform.CenterX = position.X;
            //transform.CenterY = position.Y;
            //transform.ScaleX *= zoom;
            //transform.ScaleY *= zoom;
        }

        private void ImgShow_MouseWheel4(object sender, MouseWheelEventArgs e)
        {
            //Image image = sender as Image;
            //System.Windows.Point position = e.GetPosition(image);
            //ScaleTransform transform = image.LayoutTransform as ScaleTransform;

            //double zoom = e.Delta > 0 ? 1.1 : 0.9;

            //transform.CenterX = position.X;
            //transform.CenterY = position.Y;
            //transform.ScaleX *= zoom;
            //transform.ScaleY *= zoom;
        }




        private void ImgShow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (combox.SelectedIndex == 0)
            {
                util.Image_SelectedIndex = 1;
                border1.BorderBrush = Brushes.Transparent;
            }
            else
            {
                util.Image_SelectedIndex = 1;
                border1.BorderBrush = Brushes.Green;
            }

        }

        private void ImgShow2_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            util.Image_SelectedIndex = 2;
            border2.BorderBrush = Brushes.Green;
        }

        private void ImgShow3_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            util.Image_SelectedIndex = 3;
            border3.BorderBrush = Brushes.Green;
        }

        private void ImgShow4_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            util.Image_SelectedIndex = 4;
            border4.BorderBrush = (System.Windows.Media.Brush)new BrushConverter().ConvertFrom("#33FF3C");
        }
        /// <summary>
        /// //Height="720" Width="1385"
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void combox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        //{
        //    util.ComboBox_SelectedIndex = combox.SelectedIndex;

        //    //if (Allzoom == null)
        //    //{
        //    //    MessageBox.Show("Allzoom 控件未初始化");
        //    //    return;
        //    //}

        //    if (combox.SelectedIndex == 0)
        //    {
        //        border1.Width = 1385;
        //        border1.Height = 720;
        //        border2.Height = 0;
        //        border2.Width = 0;
        //        border3.Height = 0;
        //        border3.Width = 0;
        //        border4.Height = 0;
        //        border4.Width = 0;
        //        border1.BorderBrush = brush;

        //        //Allzoom.Visibility = Visibility.Hidden;

        //    }
        //    if (combox.SelectedIndex == 1)
        //    {
        //        border1.Width = 1385 / 2;
        //        border1.Height = 720;
        //        border2.Height = 720;
        //        border2.Width = 1385 / 2;
        //        border3.Height = 0;
        //        border3.Width = 0;
        //        border4.Height = 0;
        //        border4.Width = 0;

        //        //Allzoom.Visibility = Visibility.Visible;

        //    }
        //    if (combox.SelectedIndex == 2)
        //    {
        //        border1.Width = 1385 / 2;
        //        border1.Height = 720 / 2;
        //        border2.Height = 720 / 2;
        //        border2.Width = 1385 / 2;
        //        border3.Height = 720 / 2;
        //        border3.Width = 1385 / 2;
        //        border4.Height = 720 / 2;
        //        border4.Width = 1385 / 2;

        //        //Allzoom.Visibility = Visibility.Visible;

        //    }

        //    border1.UpdateLayout();
        //    border2.UpdateLayout();
        //    border3.UpdateLayout();
        //    border4.UpdateLayout();

        //    ResetImageRenderTransform(ImgShow);
        //    ResetImageRenderTransform(ImgShow2);
        //    ResetImageRenderTransform(ImgShow3);
        //    ResetImageRenderTransform(ImgShow4);


        //}



        private void combox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            util.ComboBox_SelectedIndex = combox.SelectedIndex;

            if (combox.SelectedIndex == 0)
            {
                border1.Width = 1385;
                border1.Height = 750;
                border2.Width = 0;
                border2.Height = 0;
                border3.Width = 0;
                border3.Height = 0;
                border4.Width = 0;
                border4.Height = 0;
            }
            else if (combox.SelectedIndex == 1)
            {
                border1.Width = 1385 / 2;
                border1.Height = 750;
                border2.Width = 1385 / 2;
                border2.Height = 750;
                border3.Width = 0;
                border3.Height = 0;
                border4.Width = 0;
                border4.Height = 0;
            }
            else if (combox.SelectedIndex == 2)
            {
                border1.Width = 1385 / 2;
                border1.Height = 750 / 2;
                border2.Width = 1385 / 2;
                border2.Height = 750 / 2;
                border3.Width = 1385 / 2;
                border3.Height = 750 / 2;
                border4.Width = 1385 / 2;
                border4.Height = 750 / 2;
            }


            ResetBorderAndImage(border1, ImgShow);
            ResetBorderAndImage(border2, ImgShow2);
            ResetBorderAndImage(border3, ImgShow3);
            ResetBorderAndImage(border4, ImgShow4);


            border1.UpdateLayout();
            border2.UpdateLayout();
            border3.UpdateLayout();
            border4.UpdateLayout();


            TriggerZoom(ImgShow, border1);
            TriggerZoom(ImgShow2, border2);
            TriggerZoom(ImgShow3, border3);
            TriggerZoom(ImgShow4, border4);
        }




        private void ResetBorderAndImage(System.Windows.Controls.Border border, Image image)
        {
            border.Visibility = border.Width > 0 && border.Height > 0 ? Visibility.Visible : Visibility.Collapsed;

            // 重新设置 Image 的 RenderTransform 属性
            ResetImageRenderTransform(image);
            // 更新 Border 的 Clip 属性
            ResetBorderClip(border);
        }

        private void ResetImageRenderTransform(Image image)
        {
            if (image.RenderTransform is ScaleTransform transform)
            {
                transform.ScaleX = 1;
                transform.ScaleY = 1;
                transform.CenterX = 0;
                transform.CenterY = 0;
            }
        }

        private void ResetBorderClip(System.Windows.Controls.Border border)
        {
            if (border.ActualWidth > 0 && border.ActualHeight > 0)
            {
                var clipRect = new RectangleGeometry(new Rect(0, 0, border.ActualWidth, border.ActualHeight));
                border.Clip = clipRect;
            }
        }

        private void TriggerZoom(Image image, System.Windows.Controls.Border border)
        {
            if (border.Visibility == Visibility.Visible && image.Source != null)
            {
                ApplyZoomToImage(image, 1, new System.Windows.Point(border.ActualWidth / 2, border.ActualHeight / 2), border);
            }
        }

        //private void combox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        //{
        //    int selectedIndex = combox.SelectedIndex;
        //    // 定义所有图片框的大小和可见性
        //    List<Border> borders = new List<Border> { border1, border2, border3, border4 };
        //    List<Image> images = new List<Image> { ImgShow, ImgShow2, ImgShow3, ImgShow4 };

        //    // 先设置所有图片框为隐藏
        //    foreach (var border in borders)
        //    {
        //        border.Width = 0;
        //        border.Height = 0;
        //    }

        //    // 根据选择设置相应图片框的大小和可见性
        //    if (selectedIndex == 0)
        //    {
        //        SetBorderSize(border1, 1385, 720, brush);
        //    }
        //    else if (selectedIndex == 1)
        //    {
        //        SetBorderSize(border1, 1385 / 2, 720, brush);
        //        SetBorderSize(border2, 1385 / 2, 720, Brushes.White);
        //    }
        //    else if (selectedIndex == 2)
        //    {
        //        SetBorderSize(border1, 1385 / 2, 720 / 2, brush);
        //        SetBorderSize(border2, 1385 / 2, 720 / 2, Brushes.White);
        //        SetBorderSize(border3, 1385 / 2, 720 / 2, Brushes.White);
        //        SetBorderSize(border4, 1385 / 2, 720 / 2, Brushes.White);
        //    }
        //}

        private void SetBorderSize(System.Windows.Controls.Border border, double width, double height, System.Windows.Media.Brush brush)
        {
            border.Width = width;
            border.Height = height;
            border.BorderBrush = brush;
            border.Visibility = width > 0 && height > 0 ? Visibility.Visible : Visibility.Collapsed;
        }




        private void MaxBtn_Click(object sender, RoutedEventArgs e)
        {
            if (WindowState == WindowState.Maximized)
            {
                WindowState = WindowState.Normal;
            }
            else
            {
                this.WindowState = WindowState.Maximized;
            }

        }

        private void border1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (combox.SelectedIndex == 0)
            {
                util.Image_SelectedIndex = 1;
                border1.BorderBrush = Brushes.Transparent;
            }
            else
            {
                util.Image_SelectedIndex = 1;
                border1.BorderBrush = brush;
                border2.BorderBrush = Brushes.White;
                border3.BorderBrush = Brushes.White;
                border4.BorderBrush = Brushes.White;
            }
        }

        private void border2_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            util.Image_SelectedIndex = 2;
            border2.BorderBrush = brush;
            border1.BorderBrush = Brushes.White;
            border3.BorderBrush = Brushes.White;
            border4.BorderBrush = Brushes.White;
        }

        private void border3_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            util.Image_SelectedIndex = 3;
            border3.BorderBrush = brush;
            border2.BorderBrush = Brushes.White;
            border1.BorderBrush = Brushes.White;
            border4.BorderBrush = Brushes.White;
        }

        private void border4_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            util.Image_SelectedIndex = 4;
            border4.BorderBrush = brush;
            border1.BorderBrush = Brushes.White;
            border2.BorderBrush = Brushes.White;
            border3.BorderBrush = Brushes.White;
        }


        private void SetImageSource(ListControlModel model)
        {
            switch (util.ComboBox_SelectedIndex)
            {
                case 0:
                    break;
                case 1:

                    break;
            }
        }


        Mat SetTransparnt(Mat mat)
        {
            Mat res = new Mat();
            Image<Bgra, byte> src = mat.ToImage<Bgra, byte>();
            for (int i = 0; i < src.Rows; i++)
            {
                for (int j = 0; j < src.Cols; j++)
                {
                    if ((src.Data[i, j, 0] == 0 && src.Data[i, j, 1] == 61 && src.Data[i, j, 2] == 61) || (src.Data[i, j, 0] == 0 && src.Data[i, j, 1] == 60 && src.Data[i, j, 2] == 60))
                    {
                        src.Data[i, j, 0] = 0;
                        src.Data[i, j, 1] = 0;
                        src.Data[i, j, 2] = 0;
                    }
                }
            }
            CvInvoke.CvtColor(src.Mat, src.Mat, ColorConversion.Bgr2Bgra);
            for (int i = 0; i < src.Rows; i++)
            {
                for (int j = 0; j < src.Cols; j++)
                {
                    if ((src.Data[i, j, 0] == 0 && src.Data[i, j, 1] == 0 && src.Data[i, j, 2] == 0))
                    {
                        src.Data[i, j, 3] = 0;
                    }
                }
            }
            return src.Mat;
        }


        int bSums(Mat src)
        {
            Image<Bgr, byte> image = src.ToImage<Bgr, byte>();
            int counter = 0;
            for (int i = 0; i < image.Rows; i++)
            {
                for (int j = 0; j < image.Cols; j++)
                {
                    if ((image.Data[i, j, 0] == 255) && (image.Data[i, j, 0] == 255) && (image.Data[i, j, 0] == 255))
                    {
                        counter++;
                    }
                }
            }
            return counter;
        }

        Mat ColorTemprature(Mat input, int n)
        {
            Image<Bgr, byte> srcImage = input.ToImage<Bgr, byte>();
            Mat tem = input.Clone();
            Image<Bgr, byte> result = tem.ToImage<Bgr, byte>();
            int level = n / 2;
            for (int i = 0; i < srcImage.Rows; ++i)
            {
                //byte* ptr =(byte*)
                for (int j = 0; j < srcImage.Cols; ++j)
                {
                    int R, G, B;
                    R = (int)(srcImage.Data[i, j, 2] + level);
                    G = (int)(srcImage.Data[i, j, 1] + level);
                    B = (int)(srcImage.Data[i, j, 0] - level);
                    if (R > 255)
                        //R = 255;
                        result.Data[i, j, 2] = 255;
                    else if (R < 0)
                        //R = 0;
                        result.Data[i, j, 2] = 0;
                    else
                        result.Data[i, j, 2] = (byte)R;
                    if (G > 255)
                        //G = 255;
                        result.Data[i, j, 1] = 255;
                    else if (G < 0)
                        //G = 0;
                        result.Data[i, j, 1] = 0;
                    else
                        result.Data[i, j, 1] = (byte)G;
                    if (B > 255)
                        //B = 255;
                        result.Data[i, j, 0] = 255;
                    else if (B < 0)
                        // B = 0;
                        result.Data[i, j, 0] = 0;
                    else
                        result.Data[i, j, 0] = (byte)B;
                    //result.Data[i, j, 0] = (byte)B;
                    //result.Data[i, j, 1] = (byte)G;
                    //result.Data[i, j, 2] = (byte)R;
                    tem = result.Mat;


                }
            }
            return tem;
        }


        private ImageSource CreateTransparentImage(int width, int height)
        {
            // 创建一个 WriteableBitmap，初始化为指定宽度和高度
            WriteableBitmap bitmap = new WriteableBitmap(width, height, 96, 96, PixelFormats.Bgra32, null);

            // 锁定 WriteableBitmap 以便可以直接访问像素缓冲区
            bitmap.Lock();

            // 获取像素缓冲区的大小
            int size = width * height * 4; // 每个像素 4 个字节（BGRA 格式）

            // 创建一个透明的像素数组
            byte[] pixels = new byte[size];
            for (int i = 0; i < size; i += 4)
            {
                pixels[i] = 0;     // Blue
                pixels[i + 1] = 0; // Green
                pixels[i + 2] = 0; // Red
                pixels[i + 3] = 0; // Alpha (透明)
            }

            // 使用 WritePixels 方法将像素数据写入 WriteableBitmap
            bitmap.WritePixels(new Int32Rect(0, 0, width, height), pixels, width * 4, 0);

            // 解锁 WriteableBitmap
            bitmap.Unlock();

            return bitmap;
        }


        private void ImgProcess_Click(object sender, RoutedEventArgs e)
        {
            BitmapSource image = null;
            try
            {
                if (Image_SelectedIndex == 1)
                {
                    image = (BitmapSource)ImgShow.Source;
                }
                else if (Image_SelectedIndex == 2)
                {
                    image = (BitmapSource)ImgShow2.Source;
                }
                else if (Image_SelectedIndex == 3)
                {
                    image = (BitmapSource)ImgShow3.Source;
                }
                else if (Image_SelectedIndex == 4)
                {
                    image = (BitmapSource)ImgShow4.Source;
                }
            }
            catch (Exception)
            {

            }
            finally
            {
                ImgProcessView imgProcessView = new ImgProcessView(image);
                imgProcessView.Owner = this;
                imgProcessView.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                imgProcessView.ShowDialog();
            }


        }

        private void Border_Enter(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                try
                {
                    RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(1380, 740, 96d, 96d, PixelFormats.Pbgra32);
                    renderTargetBitmap.Render(ink);

                    string rootpath = AppDomain.CurrentDomain.BaseDirectory;
                    string filename = DateTime.Now.ToString("yyyyMMddHHmmss") + ".bmp";
                    string path = System.IO.Path.Combine(rootpath, filename);

                    using (FileStream fileStream = new FileStream(path, FileMode.Create))
                    {
                        BmpBitmapEncoder encoder = new BmpBitmapEncoder();
                        encoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
                        encoder.Save(fileStream);
                    }

                    ListControlModel model = new ListControlModel();
                    model.Name = System.IO.Path.GetFileName(path);
                    model.ImageName = filename;
                    model.ImgPath = path;

                    newDelegate?.Invoke(this, model);
                }
                catch
                {

                }
            }
        }

        private void Set_Click(object sender, RoutedEventArgs e)
        {
            OSDView oSDView = new OSDView();
            oSDView.Owner = this;
            oSDView.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            oSDView.ShowDialog();
        }


        private void OSDView_osodDelegate(object sender, OSODModel e)
        {
            //if (e.Multiplier == 16)
            //{
            //    selectedMultiplier = e.Multiplier * 1.39;
            //}
            selectedMultiplier = e.Multiplier * 1.39 * zoomindex;
            Dispatcher.Invoke(() =>
            {
                if (e.OSODindex == 0)
                {
                    indexbox.Text = "OS";
                }
                else if (e.OSODindex == 1)
                {
                    indexbox.Text = "OD";
                }
                else
                {
                    indexbox.Text = "";
                }
            });
        }

        //private void save_Click(object sender, RoutedEventArgs e)
        //{
        //    try
        //    {
        //        RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(1380, 740, 96d, 96d, PixelFormats.Pbgra32);
        //        renderTargetBitmap.Render(ink);

        //        string rootpath = AppDomain.CurrentDomain.BaseDirectory;
        //        string filename = DateTime.Now.ToString("yyyyMMddHHmmss") + ".bmp";
        //        string path = System.IO.Path.Combine(rootpath, filename);

        //        using (FileStream fileStream = new FileStream(path, FileMode.Create))
        //        {
        //            BmpBitmapEncoder encoder = new BmpBitmapEncoder();
        //            encoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
        //            encoder.Save(fileStream);
        //        }

        //        ListControlModel model = new ListControlModel();
        //        model.Name = System.IO.Path.GetFileName(path);
        //        model.ImageName = filename;
        //        model.ImgPath = path;

        //        newDelegate?.Invoke(this , model);
        //    }
        //    catch
        //    {

        //    }
        //}


    }
}
